#include "comm.h"

void Usage(char *proc)
{
  std::cout << "Usage\n\t" << proc << "port" << std::endl;
}

int main(int argc, char *argv[])
{
  if (argc != 2)
  {
    Usage(argv[0]);
    return 0;
  }

  // const uint16_t port = 8606;
  uint16_t port = atoi(argv[1]);
  int sock = socket(AF_INET, SOCK_DGRAM, 0);
  if (sock < 0)
  {
    std::cerr << "socket create failed" << errno << std::endl;
    return 1;
  }

  struct sockaddr_in local;
  memset(&local, 0, sizeof(local));
  local.sin_family = AF_INET;
  local.sin_port = htons(port);
  local.sin_addr.s_addr = INADDR_ANY;

  if (bind(sock, (struct sockaddr *)&local, sizeof(local)) < 0)
  {
    std::cerr << "bind failed" << errno << std::endl;
    return 2;
  }
  // 提供服务
  bool quit = false;
  char buffer[1024] = {0};
  while (!quit)
  {
    struct sockaddr_in src_addr;
    socklen_t len = sizeof(src_addr);

    ssize_t size = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&src_addr, &len);
    if (size > 0)
    {
      buffer[size] = 0;
      //std::cout << "client say:" << buffer << std::endl;
      FILE* fp = popen(buffer, "r");
      char line[1024] = {0};
      std::string echo_hello;
      while (fgets(line, sizeof(line), fp) != NULL){
        echo_hello += line;
      }
      pclose(fp);
      echo_hello += "...\n";
      sendto(sock, echo_hello.c_str(), echo_hello.size(), 0, (struct sockaddr *)&src_addr, len);
    }
    
  }
  return 0;
}
